<template>
  <a-modal title-align="start" title="提交工厂" :mask-closable="false" v-model:visible="showvisible" @cancel="showvisible = false" :width="1200">
    <div style="color: red">注意：如果您选择的供应商并未注册使用ERP系统，则提交之后该单子直接进入到“生产中”状态</div>
    <a-table :data="tableData" size="mini" :pagination="false" :scroll="{ x: '100%', y: '400px' }" class="table-two-line mt10">
      <template #columns>
        <a-table-column title="图片" #cell="{ record }" :width="50">
          <a-image @click="showBigImg(record)" :preview="false" :src="$extract(props.getPicList(record)[0], 'url')" width="40" height="40" />
        </a-table-column>
        <a-table-column title="产品SKU" #cell="{ record }" :width="120">
          {{ $extract(record, 'product.productSku') }}
        </a-table-column>
        <a-table-column title="销售公司/销售员" #cell="{ record }" :width="140">
          <div>{{ record.companyName }}</div>
          <div>{{ $extract(record, 'saler.name') }}</div>
        </a-table-column>
        <a-table-column title="定制编号" #cell="{ record }" :width="80">
          {{ record.customCode }}
        </a-table-column>
        <a-table-column title="数量" #cell="{ record }" :width="60">
          {{ record.qtyPurchase }}
        </a-table-column>
        <a-table-column title="定制类型" #cell="{ record }" :width="80">
          {{ $extract(record, 'customInfo.customType') }}
        </a-table-column>
        <a-table-column title="材质" #cell="{ record }" :width="60">
          {{ $extract(record, 'customInfo.material') }}
        </a-table-column>
        <a-table-column :width="160">
          <template #title>
            <a-popover content="材质单价默认取当日最新的材质报价。如果是由采购部提供毛坯半成品去加工的，则无需使用材质单价取计算结算费用。">
              <p>
                <span class="required">材质单价(元/g)</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <a-space>
              <a-input placeholder="请输入" v-model="record.amtAvgMaterial" />
              <a-button size="small" class="gray-outline" @click="setGloableDate(rowIndex, record, 'amtAvgMaterial')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </template>
        </a-table-column>
        <a-table-column :width="160">
          <template #title>
            <a-popover content="单件加工费是指生产1件定制品，供应商收取的加工费，默认去获取该产品上一个单子的加工费">
              <p>
                <span class="required">单件加工费</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <a-space>
              <a-input placeholder="请输入" v-model="record.amtAvgProcess" />
              <a-button size="small" class="gray-outline" @click="setGloableDate(rowIndex, record, 'amtAvgProcess')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </template>
        </a-table-column>
        <a-table-column :width="180">
          <template #title>
            <a-popover content="选择一个能生产该产品的供应商。">
              <p>
                <span class="required">供应商</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <a-space>
              <a-select style="width: 120px" @change="changeCompany($event, record)" placeholder="请选择" :trigger-props="{ autoFitPopupMinWidth: true }" allow-search allow-clear v-model="record.supplierCompany.companyCode">
                <a-option v-for="(item, index) of supperList" :key="index" :value="item.companyCode">{{ item.supplierName }}</a-option>
              </a-select>
              <a-button size="small" class="gray-outline" @click="setGloableDate(rowIndex, record, 'supplierCompany')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </template>
        </a-table-column>
        <a-table-column :width="240">
          <template #title>
            <a-popover content="跟供应商结算的税率。">
              <p>
                <span>税率</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <a-space>
              <div class="flex">
                <a-select style="width: 90px" v-model="record.includeTax">
                  <a-option :value="1">含税</a-option>
                  <a-option :value="0">不含税</a-option>
                </a-select>
                <a-select style="width: 80px" v-model="record.taxRate">
                  <a-option :value="3">3%</a-option>
                  <a-option :value="13">13%</a-option>
                </a-select>
              </div>
              <a-button size="small" class="gray-outline" @click="setGloableDate(rowIndex, record, 'includeTax')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </template>
        </a-table-column>
        <a-table-column :width="180">
          <template #title>
            <a-popover :width="300">
              <p>
                <span>半成品领用仓</span>
                <icon-question-circle />
              </p>

              <template #content>
                <p>这里指定了半成品的领用仓库，则可以获取到可用库存和单价，同时会锁定该半产品的库存，直到供应商交货了才会扣减掉</p>
                <p>此处务必请注意：</p>
                <p>1、如果选择了无需领料，则表示该定制无需毛坯，跟供应商结算的时候需要包含材质费用（材质单价*材质重量）</p>
                <p>2、如果选择了“番禺半成品仓”则库存所属人必须是销售员本人的</p>
              </template>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <a-space>
              <a-select style="width: 120px" @change="changeWarehouse($event, record)" placeholder="请选择" :trigger-props="{ autoFitPopupMinWidth: true }" allow-search allow-clear v-model="record.semiWarehouseCode">
                <a-option v-for="(item, index) of warehouseList" :key="index" :value="item.warehouseCode">{{ item.warehouseName }}</a-option>
              </a-select>
              <a-button size="small" class="gray-outline" @click="setGloableDate(rowIndex, record, 'semiWarehouseCode')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </template>
        </a-table-column>
        <a-table-column :width="140">
          <template #title>
            <a-popover content="如果选择了物料领用仓，则在此显示该毛坯产品在仓库的可用数量和库存单价">
              <p>
                <span>半成品库存/单价</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record }"> {{ record.SemiGoodsInventory ? record.SemiGoodsInventory : '~' }}/{{ record.supplierCloseCost.amtAvgSemiStock ? `￥${record.supplierCloseCost.amtAvgSemiStock}` : '~' }}</template>
        </a-table-column>
        <a-table-column :width="60" title="操作" #cell="{ rowIndex }" fixed="right">
          <a-button type="text" style="color: red" @click="tableData.splice(rowIndex, 1)">移除 </a-button>
        </a-table-column>
      </template>
    </a-table>

    <template #footer class="modal-footer">
      <a-button @click="showvisible = false">取消</a-button>
      <a-button type="primary" :loading="submitLoading" @click="submit">确定</a-button>
    </template>
  </a-modal>

  <a-image-preview-group v-model:visible="visible" infinite :srcList="srcList" />
</template>

<script lang="ts" setup>
  import { onMounted, ref, computed } from 'vue'
  import { findMaterialQuotePage } from '@/api/system'
  import { findSupperList, queryInventory, listLatestCustomOrderPurchase, findSaasAndErpWarehouse } from '@/api/purchase'
  import { findWarehouseListByParam } from '@/api/warehouse'
  import { batchPurchaseSumbitSupplier } from '@/api/purchase'
  import { Message } from '@arco-design/web-vue'
  let props = defineProps(['modelValue', 'list', 'getPicList', 'info'])
  let emits = defineEmits(['save', 'update:modelValue'])
  let showvisible = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })
  let selCompanyId = ref('')
  let tableData = ref([])
  let srcList = ref([])
  let materialList = ref([])
  let supperList = ref([])
  let warehouseList = ref([])
  let visible = ref(false)
  let tableLoading = ref(false)
  let submitLoading = ref(false)
  const init = () => {
    props.list.forEach((e: any) => {
      let obj = {
        ...e,
        ...e.supplierCloseCost,
        amtAvgMaterial: e.supplierCloseCost?.amtAvgMaterial || '',
        amtAvgProcess: e.supplierCloseCost?.amtAvgProcess || '',
        id: e.id,
        includeTax: 1,
        semiNoPick: true,
        semiWarehouseCode: e.supplierCloseCost?.semiWarehouseCode || '无需领料',
        semiWarehouseName: e.supplierCloseCost?.semiWarehouseName || '无需领料',
        supplierCompany: e.supplierCloseCost?.supplierCompany?.companyId
          ? e.supplierCloseCost?.supplierCompany
          : {
              companyId: '',
              companyName: '',
            },
        taxRate: e.supplierCloseCost?.taxRate || 3,
      }

      // 供应商的id是供应商列表的code
      if (obj.supplierCloseCost?.supplierCompany?.companyId) {
        obj.supplierCloseCost.supplierCompany.companyCode = obj.supplierCloseCost.supplierCompany.companyId
      }

      if (obj.semiWarehouseCode != '无需领料') {
        obj.semiNoPick = false
      }

      if (!obj.supplierCloseCost) {
        obj.supplierCloseCost = {}
      }

      // 放一个材质报价
      materialList.value.forEach((e: any) => {
        let materialType = obj.customInfo?.material
        if (materialType === e.productName) {
          obj.amtAvgMaterial = e.quotePrice
        }
      })
      tableData.value.push(obj)
    })

    tableData.value.forEach((e: any) => {
      console.log(e)

      if (e.supplierCloseCost?.semiWarehouseCode && e.supplierCloseCost?.semiWarehouseCode !== '无需领料') getInventory(e)
    })

    getSinglePrice()
  }

  const showBigImg = (item: any) => {
    let arr = props.getPicList(item)
    srcList.value = arr.map((e: any) => e.url)
    visible.value = true
  }

  const submit = async () => {
    for (let i = 0; i < tableData.value.length; i++) {
      const el: any = tableData.value[i]
      if (!el.amtAvgMaterial) {
        return Message.error('请填写材质单价')
      }
      if (!el.amtAvgProcess) {
        return Message.error('请填写单件加工费')
      }
      if (!el.supplierCompany.companyId) {
        return Message.error('请选择供应商')
      }
    }

    let arr: any = []
    tableData.value.forEach((e: any) => {
      let obj = {
        ...e,
        supplierCloseCost: {
          amtAvgMaterial: e.amtAvgMaterial,
          amtAvgProcess: e.amtAvgProcess,
          amtAvgSemiStock: e.amtAvgSemiStock,
          amtChain: e.amtChain,
          amtMaterial: e.amtMaterial,
          amtOther: e.amtOther,
          amtProcess: e.amtProcess,
          amtStone: e.amtStone,
          amtTax: e.amtTax,
          amtTotal: e.amtTotal,
          attritionRate: e.attritionRate,
          includeTax: e.includeTax,
          semiNoPick: e.semiNoPick,
          semiSupplier: e.semiSupplier,
          semiWarehouseCode: e.semiWarehouseCode,
          semiWarehouseName: e.semiWarehouseName,
          supplierCompany: e.supplierCompany,
          taxRate: e.taxRate,
          wgtAttrition: e.wgtAttrition,
          wgtContinueAttrition: e.wgtContinueAttrition,
          wgtNetMaterial: e.wgtNetMaterial,
        },
      }
      arr.push(obj)
    })

    try {
      let params = {
        list: arr,
      }
      submitLoading.value = true
      const res: any = await batchPurchaseSumbitSupplier(params)
      if (res) {
        Message.success('提交成功')
        showvisible.value = false
        emits('save')
      }
    } catch (error) {}
    submitLoading.value = false
  }

  const getMaterialQuotePage = async () => {
    const res: any = await findMaterialQuotePage()
    materialList.value = res?.data?.records || []
  }

  const getSupperList = async () => {
    const res: any = await findSupperList()
    supperList.value = res?.data || []
    console.log(supperList.value, '2222222222222')
  }

  const getWarehouse = async () => {
    const res: any = await findSaasAndErpWarehouse()
    warehouseList.value = res?.data || []
    let obj = {
      warehouseCode: '无需领料',
      warehouseName: '无需领料',
    }

    let obj1 = {
      warehouseCode: 'CK86',
      warehouseName: '番禺半成品仓',
    }

    warehouseList.value.unshift(obj1)
    warehouseList.value.unshift(obj)
  }

  const changeCompany = (id: string, data: any) => {
    let item: any = supperList.value.find((e: any) => e.companyCode === id)

    if (item) {
      data.supplierCompany.companyName = item.supplierName
      data.supplierCompany.companyId = item.companyCode
      data.supplierCompany.regist = item.register
      data.supplierCompany.supplierCode = item.supplierCode
    }
  }

  const changeWarehouse = (id: string, data: any) => {
    if (id == '无需领料') {
      data.semiNoPick = true
    } else {
      data.semiNoPick = false
    }
    let item: any = warehouseList.value.find((e: any) => e.warehouseCode === id)
    if (item) data.semiWarehouseName = item.warehouseName
    if (!data.semiNoPick) {
      getInventory(data)
    } else {
      data.SemiGoodsInventory = ''
      if (!data.supplierCloseCost) {
        data.supplierCloseCost = {}
        data.supplierCloseCost.amtAvgSemiStock = ''
      } else {
        data.supplierCloseCost.amtAvgSemiStock = ''
      }
    }
  }

  const setGloableDate = (index: number, data: any, code: string) => {
    tableData.value.forEach((e: any, i: number) => {
      if (i > index) {
        e[code] = data[code]
        if (code == 'semiWarehouseCode') {
          e.semiWarehouseName = data.semiWarehouseName
          getInventory(e)
        } else if (code == 'includeTax') {
          e.taxRate = data.taxRate
        }
      }
    })
  }

  const getInventory = async (data: any) => {
    let params = {
      skus: data.product.productSku,
      warehouseCode: data.semiWarehouseCode,
    }
    const res: any = await queryInventory(params)
    if (res) {
      let arr = res?.data || []
      data.SemiGoodsInventory = arr.reduce((acc: any, cur: any) => {
        return acc + cur.amtAvailable || 0
      }, 0)
      let priceItem = arr.find((item: any) => item.avgPrice > 0)
      // data.SemiGoodsInventory = res?.data[0]?.amtAvailable || 0
      data.amtAvgSemiStock = priceItem?.avgPrice || 0
      if (!data.supplierCloseCost) {
        data.supplierCloseCost = {}
        data.supplierCloseCost.amtAvgSemiStock = priceItem?.avgPrice || 0
      } else {
        data.supplierCloseCost.amtAvgSemiStock = priceItem?.avgPrice || 0
      }
    }
  }

  // 单次加工费
  const getSinglePrice = async () => {
    let params: any = {
      list: [],
    }
    tableData.value.forEach((e: any) => {
      let obj = {
        companyId: e.companyId,
        productSku: e.product.productSku,
        status: '130',
      }
      params.list.push(obj)
    })
    const res: any = await listLatestCustomOrderPurchase(params)

    let arr = res?.data
    tableData.value.forEach((e: any, i: number) => {
      !e.amtAvgProcess ? (e.amtAvgProcess = arr[i].latest?.supplierCloseCost?.amtAvgProcess) : ''
    })
  }

  onMounted(async () => {
    await getMaterialQuotePage()
    await getSupperList()
    await getWarehouse()
    init()
  })
</script>

<style lang="less" scoped></style>
